<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "burning2009");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();
$wechatObj->responseMsg();
class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //$this->logger("R \n".$postStr);
        /*$postStr="<xml><ToUserName><![CDATA[gh_e9906401395d]]></ToUserName>
                <FromUserName><![CDATA[oOyG3jvkl8wOgGn0BEHPqGWphh3M]]></FromUserName>
                <CreateTime>1441374079</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[黑底]]></Content>
                <MsgId>6190654530821794121</MsgId>
                </xml>";
*/
        //extract post data
        if (!empty($postStr)){
                

                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                //libxml_disable_entity_loader(true);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                
                $tp=trim($postObj->MsgType);

                switch($tp){
                    case 'text':
                        # code...
                        $this->tst($postObj);
                        break;
                }

                

        }else {
             $this->logger("R \n"."没东西啊");

            echo "";
            exit;
        }
    }

    function tst($postObj){
        $this->logger("R \n".'sb');
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName; 
        $keyword = trim($postObj->Content);

        $time = time();
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>";             
        if(!empty( $keyword ))
        {
            $msgType = "text";
            $contentStr = "Welcome to sb's wechat world!";
            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            $this->logger("R \n".$postStr);
            echo $resultStr;
        }else{
            echo "Input something...";
        }
    }
        
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


    //写日志
    private function logger($log_content){
        //日志大小 10000
        $max_size=10000;//默认字节Byte
        $log_filename='log.xml';
        if(file_exists($log_filename)&&abs(filesize($log_filename))>$max_size){
            unlink($log_filename);
        }
        //date_default_timezone_set('PRC');
        file_put_contents($log_filename, date('Y-m-d G:i:s',time()+28800).' '.$log_content."\r\n",FILE_APPEND);//双引号才换行
    }

    function pnt($ctt){
        $flnm='tmp.txt';
        unlink($flnm);
         file_put_contents($flnm, date('Y-m-d G:i:s',time()+28800)."\n".$ctt."\n",FILE_APPEND);//
    }
}

?>